<template>
  <div>
    <div class="filter">
      <button
        v-for="(tab, index) in tabs"
        :key="index"
        :class="{ active: currentTab === tab.value }"
        @click="changeTab(tab.value)"
      >
        {{ tab.label }} <span v-if="tab.count !== null">{{ tab.count }}</span>
      </button>
      <div class="floating-bar" v-if="isAnySelected">
        <button class="select-all-button" @click="toggleSelectAll" style="margin-right: 15px;">
          {{ allSelectedOnPage ? '取消全选' : '本页全选' }}
        </button>
        <button class="batch-delete-button" @click="batchDeleteExams" style="margin-right: 15px;">批量删除</button>
      </div>
      <button class="create-button" @click="toggleNewExamMenu">新建考试</button>
    </div>

    <!-- 新建问题菜单 -->
    <div v-if="newExamMenuVisible" class="new-question-menu">
      <span @click="navigateToNewExam">重新组卷</span>
      <span @click="selectExistingExam">选择试卷</span>
    </div>

    <!-- 考试列表 -->
    <div
      v-for="exam in paginatedExams"
      :key="exam.exam_id"
      class="exam-card"
      @click="navigateToExamDetail(exam.exam_id)"
      @mouseenter="exam.showActions = true"
      @mouseleave="exam.showActions = false"
    >
      <!-- 复选框 -->
      <input
        type="checkbox"
        class="exam-checkbox"
        :checked="selectedExams.has(exam.exam_id)"
        @click.stop="toggleSelection(exam.exam_id)"
      />

      <div class="exam-content">
        <div class="exam-header">
          <span class="badge" :class="statusBadgeClass(exam.status)">
            {{ statusLabel(exam.status) }}
          </span>
          <p style="font-weight:bold;">{{ exam.paper_title }}</p>
          <div v-show="exam.showActions" class="exam-actions" :key="exam.exam_id">
            <button class="edit-button" @click.stop="navigateToExamDetail(exam.exam_id)">编辑</button>
            <button class="edit-button" @click.stop="navigateToExamPublish(exam.exam_id)">发布</button>
            <button class="edit-button" @click.stop="deleteExam(exam.exam_id)">删除</button>
          </div>
        </div>
        <p>老师: {{ exam.username }}</p>
        <div style="display:flex; font-size: 12px; color: gray;">
          <p style="margin-right: 10px;">开始时间: {{ exam.start_time }}</p>
          <p style="margin-right: 10px;">结束时间: {{ exam.end_time }}</p>
          <p style="margin-right: 10px;">考试时长: {{ exam.during_time ? exam.during_time + '分钟' : '不限时' }}</p>
        </div>
      </div>
    </div>

    <!-- 分页组件 -->
    <PagiNation :currentPage="currentPage" :totalPages="totalPages" @page-change="handlePageChange" />
     <!-- 试卷库模态框 -->
  <div v-if="showExamBankDialog" class="dialog-overlay" @click.self="showExamBankDialog = false">
    <div class="dialog-content"  @click.stop>
    <!-- <div style="margin: 10px 10px 0px 20px;display: flex;font-size: 19px;font-weight: bold;justify-content: space-between;">
    <span>选择试卷 </span>
    <span class="close-btn" @click="showExamBankDialog = false">×</span>
    </div> -->
    <T_ExamBankPage 
      :is-select-mode="true"
      @paper-selected="handlePaperSelected"
    />
      <div class="dialog-actions">
        <div v-if="selectedPaper" class="selected-paper-info">
          已选试卷: {{ selectedPaper.name }} (ID: {{ selectedPaper.id }})
        </div>
        <button @click="showExamBankDialog = false" class="bac-button">取消</button>
        <button @click="confirmSelectPaper" class="confirm-button">确认选择</button>
      </div>
    </div>
  </div>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { fetchExams, deleteExams,createexamwithexistingpaper } from '@/services/api';
import PagiNation from '@/components/PagiNation.vue';
import T_ExamBankPage from './T_ExamBankPage.vue';

export default {
  name: 'OnlineExams',
  components: {
    PagiNation,
     T_ExamBankPage 
  },
  props: {
    classId: {
      type: [String, Number],
      required: true,
    },
  },
  setup(props, { emit }) {
    const showExamBankDialog = ref(false);
    const selectedPaper = ref(null);
    const currentTab = ref('全部考试');
    const currentPage = ref(1);
    const itemsPerPage = 8;
    const isLoading = ref(false);
    const tabs = ref([
      { label: '全部考试', value: '全部考试', count: null },
      { label: '未开始', value: 0, count: null },
      { label: '进行中', value: 1, count: null },
      { label: '已截止', value: 2, count: null },
    ]);
    

    const router = useRouter();
     const selectQuiz = (quiz) => {
    if (props.isSelectMode) {
      // 添加控制台日志验证事件触发
      console.log('Selected quiz:', quiz);
      emit('paper-selected', quiz);
      
      // 添加自动关闭逻辑（可选）
      // 如果需要在选择后自动关闭列表，可以在这里触发路由返回
      // router.go(-1);
    }
  };

    const navigateToExamDetail = (examId) => {
        const exam = exams.value.find(e => e.exam_id === examId);
        if (exam) {
            // 直接使用exam对象中的paper_id，不要通过localStorage中转
            console.log("当前 paperId:", exam.paper_id);  // 直接打印原始值
            
            // 正确存储到localStorage供后续使用
            localStorage.setItem('currentExamStatus', exam.status);
            localStorage.setItem('currentExamTitle', exam.paper_title);
            localStorage.setItem('currentPaperId', exam.paper_id);
            
            // 添加时间戳确保每次点击都会刷新
            localStorage.setItem('lastExamClick', Date.now().toString());
            console.log("完整考试对象:", exam);
        }
        router.push({ name: 'ExamDetail', params: { examId, semesterId: props.classId } });
    };
    const navigateToExamPublish = (examId) => {
        const exam = exams.value.find(e => e.exam_id === examId);
        if (exam) {
            // 直接使用exam对象中的paper_id，不要通过localStorage中转
            console.log("当前 paperId:", exam.paper_id);  // 直接打印原始值
            
            // 正确存储到localStorage供后续使用
            localStorage.setItem('currentExamStatus', exam.status);
            localStorage.setItem('currentExamTitle', exam.paper_title);
            localStorage.setItem('currentPaperId', exam.paper_id);
            
            // 添加时间戳确保每次点击都会刷新
            localStorage.setItem('lastExamClick', Date.now().toString());
            console.log("完整考试对象:", exam);
        }
        router.push({ name: 'ExamSettings', params: { examId, semesterId: props.classId } });
    };
    
    const handlePaperSelected = (paper) => {
       console.log('完整试卷对象:', paper);
      selectedPaper.value = paper;
      console.log('Selected paper ID:', paper?.paper_id); // 添加可选链操作符
    };
    const exams = ref([]);
    const selectedExams = ref(new Set());
    const isAnySelected = computed(() => selectedExams.value.size > 0);

    const allSelectedOnPage = computed(() => {
      if (paginatedExams.value.length === 0) return false;
      return paginatedExams.value.every(exam => selectedExams.value.has(exam.exam_id));
    });

    const toggleSelectAll = () => {
      if (allSelectedOnPage.value) {
        paginatedExams.value.forEach(exam => {
          selectedExams.value.delete(exam.exam_id);
        });
      } else {
        paginatedExams.value.forEach(exam => {
          selectedExams.value.add(exam.exam_id);
        });
      }
    };

    // 在loadExams方法中修改数据映射逻辑
const loadExams = async () => {
  try {
    const response = await fetchExams(props.classId);
    if (response.data.status === 1) {
      exams.value = response.data.data.map((exam) => ({
        ...exam,
        showActions: false,
        // 添加paper_id字段映射（需确保后端实际返回该字段）
        paper_id: exam.paper_id || null
      }));
      
      // 添加调试日志
      console.log('考试列表数据:', exams.value);
      
      tabs.value.forEach((tab) => {
        if (tab.value === '全部考试') {
          tab.count = exams.value.length;
        } else {
          tab.count = exams.value.filter((exam) => exam.status === tab.value).length;
        }
      });
    }
  } catch (error) {
    console.error('加载考试失败:', error);
  }
};


    const filteredExams = computed(() => {
      if (currentTab.value === '全部考试') {
        return exams.value;
      } else {
        return exams.value.filter((exam) => exam.status === currentTab.value);
      }
    });

    const paginatedExams = computed(() => {
      const start = (currentPage.value - 1) * itemsPerPage;
      const end = start + itemsPerPage;
      return filteredExams.value.slice(start, end);
    });

    const totalPages = computed(() => {
      return Math.ceil(filteredExams.value.length / itemsPerPage);
    });

    const changeTab = (tabValue) => {
      currentTab.value = tabValue;
      currentPage.value = 1;
      selectedExams.value.clear();
    };

    const handlePageChange = (newPage) => {
      currentPage.value = newPage;
      selectedExams.value.clear();
    };

    const statusLabel = (status) => {
      switch (status) {
        case 0:
          return '未开始';
        case 1:
          return '进行中';
        case 2:
          return '已截止';
        default:
          return '未知状态';
      }
    };

    const statusBadgeClass = (status) => {
      switch (status) {
        case 0:
          return 'badge-unstart';
        case 1:
          return 'badge-in-progress';
        case 2:
          return 'badge-closed';
        default:
          return 'badge-unknown';
      }
    };

    const navigateToNewExam = () => {
      window.location.href = `/new-exam/${props.classId}`;
    };

    const toggleSelection = (examId) => {
      if (selectedExams.value.has(examId)) {
        selectedExams.value.delete(examId);
      } else {
        selectedExams.value.add(examId);
      }
    };
    const deleteExam = async (examId) => {
      selectedExams.value = new Set([examId]);
      await batchDeleteExams();
    };
    const batchDeleteExams = async () => {
      try {
        if (selectedExams.value.size === 0) {
          ElMessage.warning('请选择要删除的考试！');
          return;
        }

        await ElMessageBox.confirm(
          `确定删除选中的 ${selectedExams.value.size} 个考试吗？`,
          '警告',
          {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
          }
        );

        const examIds = Array.from(selectedExams.value);
        const response = await deleteExams(examIds.join(','));
        
        if (response.data.status === 1) {
          ElMessage.success('删除成功！');
          selectedExams.value.clear();
          loadExams();
        } else {
          ElMessage.error('删除失败: ' + response.data.msg);
        }
      } catch (error) {
        // 用户取消操作自动捕获
      }
    };
    // 显示/隐藏新建考试菜单
    const toggleNewExamMenu = () => {
      newExamMenuVisible.value = !newExamMenuVisible.value;
    };

    const selectExistingExam = () => {
      showExamBankDialog.value = true;
    };

    const newExamMenuVisible = ref(false);

    // 添加试卷选择确认方法
const confirmSelectPaper = async () => {
   console.log('创建考试参数:', {
    sem_id: props.classId,
    paper_id: selectedPaper.value?.id,
    tech_id: localStorage.getItem('id')
  });
  if (!selectedPaper.value) {
      ElMessage.warning('请先选择试卷');
      return;
    }

  try {
    const response = await createexamwithexistingpaper({
      sem_id: props.classId,
      paper_id: selectedPaper.value.id,
      tech_id: localStorage.getItem('id')
    });
    
    if (response.data.status === 1) {
      ElMessage.success('考试创建成功');
      loadExams();
      showExamBankDialog.value = false;
      selectedPaper.value = null;
    }
  } catch (error) {
    console.error('创建考试失败:', error);
    ElMessage.error('考试创建失败: ' + error.message);
  } finally {
    isLoading.value = false;
  }
};
    onMounted(() => {
      loadExams();
    });

    return {
      currentTab,
      tabs,
      currentPage,
      totalPages,
      exams,
      filteredExams,
      paginatedExams,
      statusLabel,
      statusBadgeClass,
      changeTab,
      handlePageChange,
      navigateToNewExam,
      navigateToExamDetail,
      navigateToExamPublish,
      selectedExams,
      isAnySelected,
      toggleSelection,
      toggleSelectAll,
      allSelectedOnPage,
      batchDeleteExams,
      toggleNewExamMenu,
      newExamMenuVisible,
      selectExistingExam,
      showExamBankDialog,
      selectedPaper,
      confirmSelectPaper,
      T_ExamBankPage,
      createexamwithexistingpaper,
      selectQuiz,
      handlePaperSelected,
      deleteExam
    };
  },
};
</script>


<style scoped>
/* 新建考试菜单 */
.new-question-button {
  background-color: #244382;
  color: white;
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.new-question-menu {
    width: 74px;
    position: absolute;
    margin-top: -15px;
    right: 11.5vw;
    z-index: 10;
    background-color: white;
    border: 1px solid #ddd;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
    border-radius: 4px;
    padding: 10px;
    display: flex;
    flex-direction: column;
    gap: 10px;
    align-items: center;
}

.new-question-menu span {
  cursor: pointer;
  padding: 5px 0;
  color: gray;
  transition: color 0.3s;
}

.new-question-menu span:hover {
  color: #244382;
}
/* 与作业页面相似的样式 */
.filter {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.filter button {
  background: none;
  border: none;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  color: #333;
  transition: background-color 0.3s, color 0.3s;
}

.filter button.active {
  color: #244382;
  border-bottom: 2px solid #244382;
  font-weight: bold;
}

.filter .create-button {
  margin-left: auto;
  background-color: #244382;
  color: #fff;
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.filter .create-button:hover {
  background-color: #376edc;
}

.exam-card {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  position: relative;
  transition: transform 0.3s;
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.exam-card:hover {
  transform: translateY(-5px);
  background-color: #f0f0f0;
}

.exam-checkbox {
  margin-right: 15px;
  margin-top: 5px;
  cursor: pointer;
  margin-top: 20px;
}

.exam-content {
  flex: 1;
}

.exam-header {
  display: flex;
  align-items: center;
  gap: 15px;
  position: relative;
}

.badge {
  display: inline-block;
  padding: 5px 10px;
  border-radius: 12px;
  font-size: 14px;
}

.badge-unstart {
  background-color: #cae2f9;
  color: #519bd5;
}

.badge-in-progress {
  background-color: #d6ffdb;
  color: #3b995c;
}

.badge-closed {
  background-color: #f0f0f0cc;
  color: #666;
}

.exam-actions {
  margin-left: auto;
  display: flex;
  gap: 10px;
  position: absolute;
  right: 0;
  top: 0;
}

.edit-button,
.delete-button {
  background-color: transparent;
  border: none;
  cursor: pointer;
  color: #244382;
  font-size: 14px;
  transition: color 0.3s;
}

.edit-button:hover,
.delete-button:hover {
  color: #1e3661;
}

.floating-bar {
  width: 42.5%;
  text-align: right;
}

.floating-bar button {
  background-color: #244382;
  color: #fff;
  border: none;
  padding: 10px 15px;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s, color 0.3s;
}

.floating-bar button:hover {
  background-color: #376edc;
}
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.close-btn {
  cursor: pointer;
  font-size: 24px;
}

.dialog-actions {
  margin: 30px 0px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.selected-paper-info {
  font-size: 14px;
  color: #666;
  margin-right: auto;
  margin-left: 20px;
}

.confirm-button {
  font-size: 15px;
  margin-right: 20px;
  background-color: #125AA2;
  color: #fff;
  padding: 10px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}
.confirm-button:hover {
  background-color: #3987d4;
}
.bac-button {
  font-size: 15px;
  background-color: #eee;
  color: rgb(80, 80, 80);
  border: rgb(95, 95, 95);
  padding: 10px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}
.bac-button:hover{
  background-color:rgb(212, 212, 212) !important;
}
.dialog-content {
  background: white;
  border-radius: 8px;
  width: 80%;
  max-width: 1200px;
  height: 80vh;
  padding: 20px;
  display: flex;
  flex-direction: column;
  /* 添加滚动条 */
  overflow-y: scroll; /* 外层容器隐藏滚动 */
}

.dialog-content::v-deep .exam-bank-container { /* 穿透样式到子组件 */
  flex: 1;
  overflow-y: auto;
  padding: 10px 0;
}
</style>
